// pages/index/myBill/myBill.js
import request from "../../../utils/request"

Page({
  data: {
    index: 0,
    showPopup: false,
    currentBill: {},
    elderlyList: [],
    allBillList: [],
    filteredBillList: [],
    currentElderlyId: 'all',
    billDays: 0 // 存储计算后的天数
  },

  changeIndex(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      index
    }, () => this.filterBillData());
  },

  filterElderly(e) {
    const elderlyId = e.currentTarget.dataset.elderlyid;
    this.setData({
      currentElderlyId: elderlyId
    }, () => this.filterBillData());
  },

  filterBillData() {
    const {
      index,
      allBillList,
      currentElderlyId
    } = this.data;
    let filtered = [...allBillList];

    // 打印当前筛选条件，便于调试
    console.log('当前筛选条件：', {
      index, // 0-待支付，1-已支付，2-已关闭，3-全部
      currentElderlyId,
      totalOriginal: allBillList.length // 原始数据总数
    });

    // 筛选老人
    if (currentElderlyId !== 'all') {
      filtered = filtered.filter(bill => bill.elderlyId == currentElderlyId);
      console.log('筛选老人后数量：', filtered.length);
    }

    // 筛选支付状态（兼容数字和字符串）
    const statusMap = {
      0: ['0', 0], // 待支付可能的取值
      1: ['1', 1], // 已支付可能的取值
      2: ['2', 2] // 已关闭可能的取值
    };
    if (index >= 0 && index <= 2) {
      filtered = filtered.filter(bill =>
        statusMap[index].includes(bill.billTransactionStatus)
      );
      console.log(`筛选状态${index}后数量：`, filtered.length);
    }

    // 格式化数据：新增「实际应付金额」计算（预存款不足显示差额，否则0）
    const formattedBillList = filtered.map(bill => {
      // 处理空值，默认0
      const currentPayable = bill.billCurrentPayable || 0;
      const prepaymentBalance = bill.balancePrepaymentBalance || 0;
      // 计算实际应付金额
      const actualPayable = prepaymentBalance >= currentPayable ? 0 : currentPayable - prepaymentBalance;

      return {
        ...bill,
        formattedPayableAmount: (bill.billPayableAmount || 0).toFixed(2),
        formattedCheckInBedFee: (bill.checkInBedFee || 0).toFixed(2),
        formattedCheckInNursingFee: (bill.checkInNursingFee || 0).toFixed(2),
        formattedCheckInOtherFee: (bill.checkInOtherFee || 0).toFixed(2),
        formattedCheckInMedicalInsurancePayment: (bill.checkInMedicalInsurancePayment || 0).toFixed(2),
        formattedCheckInGovernmentSubsidy: (bill.checkInGovernmentSubsidy || 0).toFixed(2),
        formattedBillMonthlyPayable: (bill.billMonthlyPayable || 0).toFixed(2),
        formattedBillCurrentPayable: (bill.billCurrentPayable || 0).toFixed(2),
        formattedCheckInDeposit: (bill.checkInDeposit || 0).toFixed(2),
        formattedBillBillAmount: (bill.billBillAmount || 0).toFixed(2),
        formattedBillPrepaymentAmount: (bill.balancePrepaymentBalance || 0).toFixed(2),
        formattedActualPayable: actualPayable.toFixed(2) // 新增：格式化后的实际应付金额
      };
    });

    this.setData({
      filteredBillList: formattedBillList
    });
  },

  // 计算天数并存储到data，同时格式化弹窗数据
  showDetailModal(e) {
    const bill = e.currentTarget.dataset.bill;
    console.log("账单开始时间：", bill.billBillStartTime);
    console.log("账单结束时间：", bill.billBillEndTime);

    // 1. 计算账单周期天数
    let days = 0;
    if (bill.billBillStartTime && bill.billBillEndTime) {
      const startDate = bill.billBillStartTime.split(' ')[0];
      const endDate = bill.billBillEndTime.split(' ')[0];
      const start = new Date(startDate);
      const end = new Date(endDate);

      if (!isNaN(start.getTime()) && !isNaN(end.getTime())) {
        const timeDiff = end.getTime() - start.getTime();
        days = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
      }
    }
    console.log("计算的天数：", days);

    // 2. 格式化账单数据：新增「实际应付金额」计算
    // 处理空值，默认0
    const currentPayable = bill.billCurrentPayable || 0;
    const prepaymentBalance = bill.balancePrepaymentBalance || 0;
    // 计算实际应付金额
    const actualPayable = prepaymentBalance >= currentPayable ? 0 : currentPayable - prepaymentBalance;

    const formattedCurrentBill = {
      ...bill,
      formattedPayableAmount: (bill.billPayableAmount || 0).toFixed(2),
      formattedCheckInBedFee: (bill.checkInBedFee || 0).toFixed(2),
      formattedCheckInNursingFee: (bill.checkInNursingFee || 0).toFixed(2),
      formattedCheckInOtherFee: (bill.checkInOtherFee || 0).toFixed(2),
      formattedCheckInMedicalInsurancePayment: (bill.checkInMedicalInsurancePayment || 0).toFixed(2),
      formattedCheckInGovernmentSubsidy: (bill.checkInGovernmentSubsidy || 0).toFixed(2),
      formattedBillMonthlyPayable: (bill.billMonthlyPayable || 0).toFixed(2),
      formattedBillCurrentPayable: (bill.billCurrentPayable || 0).toFixed(2),
      formattedCheckInDeposit: (bill.checkInDeposit || 0).toFixed(2),
      formattedBillBillAmount: (bill.billBillAmount || 0).toFixed(2),
      formattedBillPrepaymentAmount: (bill.balancePrepaymentBalance || 0).toFixed(2),
      formattedActualPayable: actualPayable.toFixed(2) // 新增：格式化后的实际应付金额
    };

    // 3. 设置数据到页面
    this.setData({
      currentBill: formattedCurrentBill,
      billDays: days,
      showPopup: true
    });
  },

  closeDetailModal() {
    this.setData({
      showPopup: false,
      billDays: 0 // 重置天数
    });
  },

  goToPay(e) {
    const bill = e.currentTarget.dataset.bill;
    console.log('当前点击支付的账单信息：');
    console.log('账单ID：', bill.billId);
    console.log('本期应付金额：', bill.billCurrentPayable);
    console.log('预交款余额：', bill.balancePrepaymentBalance);

    // 1. 处理金额为null的情况，默认0
    const currentPayable = bill.billCurrentPayable || 0; // 本期应付
    const prepaymentAmount = bill.balancePrepaymentBalance || 0; // 预交款余额

    // 2. 计算：实际应付金额 = 本期应付 - 预交款余额
    const actualPayable = currentPayable - prepaymentAmount;
    console.log('计算后实际应付金额：', actualPayable);

    // 3. 根据金额判断逻辑
    if (prepaymentAmount >= currentPayable) {
      // 3.1 预交款充足：显示确认扣费弹窗
      wx.showModal({
        title: '余额充足',
        content: `本期应付 ${currentPayable.toFixed(2)} 元，预交款余额 ${prepaymentAmount.toFixed(2)} 元，可直接扣费。是否确认？`,
        confirmText: '确认扣费',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 确认支付：调用修改状态接口
            this.updateBillStatus(bill.billId, '1', currentPayable); // 状态'1'为已支付
          }
        }
      });
    } else {
      // 3.2 预交款不足：计算差额并显示确认弹窗
      const shortage = currentPayable - prepaymentAmount;
      console.log(`预交款不足！本期应付 ${currentPayable.toFixed(2)} 元，预交款余额 ${prepaymentAmount.toFixed(2)} 元，还差 ${shortage.toFixed(2)} 元`);

      // 3.2 预交款不足：弹窗确认后跳转支付页
      wx.showModal({
        title: '预交款余额不足',
        content: `本期应付 ${currentPayable.toFixed(2)} 元，预交款余额 ${prepaymentAmount.toFixed(2)} 元，还差 ${shortage.toFixed(2)} 元。是否前往支付？`,
        confirmText: '去支付',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            // 关键修复1：确保shortage是有效数字，避免NaN
            const finalShortage = isNaN(shortage) ? 0 : Number(shortage.toFixed(2));
            // 关键修复2：URL传递时用encodeURIComponent处理，避免特殊字符问题
            wx.navigateTo({
              url: `/pages/index/afford/afford?billId=${bill.billId}&amount=${encodeURIComponent(finalShortage)}&elderlyId=${bill.elderlyId}`
            });
          }
        }
      });
    }
  },

  // 调用后端修改账单状态接口
  updateBillStatus(billId, targetStatus, currentPayable) {
    request({
      url: '/financialManagement/accountEntryList/updateStatus',
      method: 'PUT',
      data: {
        id: billId,
        transactionStatus: targetStatus,
        currentPayable: currentPayable
      }
    }).then(resp => {
      console.log('修改账单状态返回：', resp.data);
      if (resp.data.code === 200) {
        wx.showToast({
          title: '支付成功',
          icon: 'success'
        });
        // 支付成功后刷新账单列表
        setTimeout(() => {
          this.getElderlyRoomInfo();
        }, 1000);
      } else {
        wx.showToast({
          title: resp.data.data || '支付失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error('支付接口调用失败：', err);
      wx.showToast({
        title: '网络异常，请重试',
        icon: 'none'
      });
    });
  },

  toMy() {
    wx.navigateBack();
  },

  async getElderlyRoomInfo() {
    const loginUserInfo = wx.getStorageSync('loginUserInfo');
    if (!loginUserInfo?.userId) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      wx.navigateTo({
        url: '/pages/my/login/login'
      });
      return;
    }

    try {
      const res = await request({
        url: '/elderly/room/info',
        method: 'GET',
        data: {
          wxUserId: loginUserInfo.userId,
          _t: new Date().getTime()
        },
        loadingText: '加载账单数据中...',
        errorText: '获取账单失败'
      });

      if (res.statusCode === 200) {
        console.log(res);
        const elderlyInfoList = Array.isArray(res.data) ? res.data : [];
        const elderlyList = [...new Map(elderlyInfoList.map(item => [item.elderlyId, item])).values()];
        const allBillList = elderlyInfoList.filter(item => item.billId);

        this.setData({
          elderlyList,
          allBillList
        }, () => this.filterBillData());
      }
    } catch (err) {
      console.error('获取账单数据异常：', err);
      wx.showToast({
        title: '网络异常，请稍后重试',
        icon: 'none'
      });
    }
  },

  // 页面加载时接收老人ID并请求数据
  onLoad(options) {
    const {
      elderlyId
    } = options;
    if (elderlyId) {
      this.setData({
        index: 3,
        currentElderlyId: elderlyId
      });
    }
    this.getElderlyRoomInfo();
  },

  // 页面显示时刷新数据（若已有数据）
  onShow() {
    if (this.data.allBillList.length > 0) {
      this.getElderlyRoomInfo();
    }
  }
});